/*
 * Copyright (c) 2015. For Intelligent Group.
 */
package com.intelligent.ispc.client.core.modal.grr;

import javax.swing.*;
import java.util.List;
import java.util.Vector;

/**
 * Created by cherry on 16/9/10.
 */

/**
 * @param <T>
 */
public class ItemShowRangeModel<T> extends DefaultComboBoxModel<T> {
    private Vector<T> comboBoxValues;
    private Object selectedValue;

    /**
     * ItemShowRangeModel constructor
     */
    public ItemShowRangeModel() {
        comboBoxValues = new Vector<>();
    }


    @Override
    public int getSize() {
        if (comboBoxValues == null) {
            return 0;
        }
        return comboBoxValues.size();
    }

    @Override
    public T getElementAt(int index) {
        if (index >= 0 && index < comboBoxValues.size()) {
            return comboBoxValues.elementAt(index);
        } else {
            return null;
        }
    }

    @Override
    public void setSelectedItem(Object anObject) {
        if ((selectedValue != null && !selectedValue.equals(anObject)) || anObject != null) {
            selectedValue = anObject;
            fireContentsChanged(this, -1, -1);
        }
    }

    @Override
    public Object getSelectedItem() {
        return selectedValue;
    }

    @Override
    public void removeAllElements() {
        if (comboBoxValues != null && comboBoxValues.size() > 0) {
            int firstIndex = 0;
            int lastIndex = comboBoxValues.size() - 1;
            comboBoxValues.removeAllElements();
            selectedValue = null;
            fireIntervalRemoved(this, firstIndex, lastIndex);
        } else {
            selectedValue = null;
        }
    }

    /**
     * set range model data source
     *
     * @param values range model data source
     */
    public void setData(List<String> values) {
        comboBoxValues = new Vector(values);
        if (getSize() > 0) {
            if (getSize() == 1) {
                selectedValue = getElementAt(0);
            } else {
                selectedValue = getElementAt(1);
            }
        }

        fireContentsChanged(this, 0, values.size());
    }
}
